from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from tools import TableStu
import pandas as pd
import sys
import shutil
import os
import new.getStudentGrades as get
import new.regretGrades as rg
import new.getTargetValue as target
import new.get_stu_info as gsi
import json
import new.gradeInput as gi
import new.convert2object as co
import new.big_function as big
import combineTest.combine as combine
class LeftWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.btn0 = QPushButton("Home",self)
        self.btn1 = QPushButton("学生名单",self)
        self.btn2 = QPushButton("成绩录入",self)
        self.btn3 = QPushButton("结果生成",self)
        self.setFixedWidth(144)
        self.init_ui()
        self.set_widget_style()
    def init_ui(self):
        pal = QPalette(self.palette())
        pal.setColor(QPalette.Background,QColor(255,255,255))
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        self.btn0.move(15,20)
        self.btn1.move(15,70)
        self.btn2.move(15,120)
        self.btn3.move(15,170)
        self.btn0.clicked.connect(self.home)
        self.btn1.clicked.connect(self.stulist)
        self.btn2.clicked.connect(self.result)
        self.btn3.clicked.connect(self.CreateResult)
    def set_widget_style(self):
        self.btn0.setStyleSheet("color:rgb(73,166,234);border:none;")
        self.btn1.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn2.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn3.setStyleSheet("color:rgb(170,170,170);border:none;")
        font = QFont("PingFang SC Regular",20)
        font.setPixelSize(20)
        self.btn0.setFont(font)
        self.btn1.setFont(font)
        self.btn2.setFont(font)
        self.btn3.setFont(font)
    def stulist(self):
        for i in range(len(self.right)):
            self.right[i].close()
        self.right[3].show()
        self.right_layout.addWidget(self.right[3])
        self.btn0.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn1.setStyleSheet("color:rgb(73,166,234);border:none;")
        self.btn2.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn3.setStyleSheet("color:rgb(170,170,170);border:none;")
    def result(self):
        for i in range(len(self.right)):
            self.right[i].close()
        self.right[1].show()
        self.right_layout.addWidget(self.right[1])
        self.btn0.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn1.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn2.setStyleSheet("color:rgb(73,166,234);border:none;")
        self.btn3.setStyleSheet("color:rgb(170,170,170);border:none;")
    def CreateResult(self):
        for i in range(len(self.right)):
            self.right[i].close()
        self.right[2].show()
        self.right_layout.addWidget(self.right[2])
        self.btn0.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn1.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn2.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn3.setStyleSheet("color:rgb(73,166,234);border:none;")
    def home(self):
        for i in range(len(self.right)):
            self.right[i].close()
        self.right[0].show()
        self.right_layout.addWidget(self.right[0])
        self.btn0.setStyleSheet("color:rgb(73,166,234);border:none;")
        self.btn1.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn2.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn3.setStyleSheet("color:rgb(170,170,170);border:none;")
    def get_widget_pointer(self,widget,layout):
        self.right = widget
        self.right_layout = layout
class TopWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()
        pal = QPalette(self.palette())
        pal.setColor(QPalette.Background,QColor(255,255,255))
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        #设置logo
        self.logo = QLabel(self)
        self.pix = QPixmap("static/cqu.jpg")
        self.pix = self.pix.scaled(39, 39, Qt.KeepAspectRatio)
        self.logo.setPixmap(QPixmap(self.pix))
        self.logo.move(5,0)
        #设置标题
        self.tittle = QLabel(self)
        self.tittle.setText("成绩管理")
        font = QFont('PingFang SC Regular')
        font.setPixelSize(20)
        self.tittle.setFont(font)
        self.tittle.move(55,0)

        self.side = QLabel(self)
        self.pic = QPixmap("static/people.jpg")
        self.pic = self.pic.scaled(42, 33, Qt.KeepAspectRatio)
        self.side.setPixmap(QPixmap(self.pic))
        self.side.move(660,0)
        self.setFixedHeight(57)
    

class Test(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(350,250,760,475)
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.layout.setSpacing(0)
        self.main_wid = QWidget()
        self.main_lay = QHBoxLayout()
        self.main_wid.setLayout(self.main_lay)
        self.left = LeftWidget()
        self.main_lay.addWidget(self.left)
        self.right = [RightWidget(),ResultWidget(),ResultCreate(),StuListWidget()]
        self.main_lay.addWidget(self.right[0])
        self.top = TopWidget()
        self.layout.addWidget(self.top)
        self.layout.addWidget(self.main_wid)
        self.left.get_widget_pointer(self.right,self.main_lay)
        self.right[0].get_widget_pointer(self.right[3].table)
class RightWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.lab1 = QLabel("课程名称",self)
        self.lab2 = QLabel("课程编号",self)
        self.lab3 = QLabel("任课老师",self)
        self.lab1.move(5,8)
        self.lab2.move(225,8)
        self.lab3.move(395,8)
        self.line1 = QLineEdit(self)
        self.line2 = QLineEdit(self)
        self.lab3 = QLabel(self)
        self.line1.move(70,5)
        self.line2.move(285,5)
        self.lab3.move(455,8)
        self.line1.setFixedWidth(150)
        self.line2.setFixedWidth(100)
        self.lab3.setFixedWidth(100)
        self.resize(600,400)
        self.score = TemplatesScore(self)
        self.score.move(0,60)
        self.result = TemplatesResult(self)
        self.result.move(300,60)
        self.init_dynamic()
    def get_widget_pointer(self,pointer):
        self.score.get_widget_pointer(pointer)
    def init_dynamic(self):
        with open("tmp/user") as f:
            line = f.read().split(",")
            truename = line[2]
            self.lab3.setText(truename)
    def init_ui(self):
        pass
class TemplatesScore(QWidget):
    def __init__(self,parent=None):
        super().__init__(parent=parent)
        self.resize(250,305)
        self.pic = QPixmap("static/upload.jpg")
        self.pic = self.pic.scaled(39, 33)
        self.lab1 = QLabel(self)
        self.lab1.setPixmap(self.pic)
        self.lab2 = QLabel(self)
        self.lab2.setText("成绩录入")
        self.lab3 = QLabel(self)
        self.lab3.setText("成绩缺少时处理方式")
        self.lab4 = QLabel(self)
        self.lab4.setText("注意：缺考和缓考，如果勾选，就计0分统计，不勾选就去除掉该学生")
        self.box1 = QCheckBox("缺考",self)
        self.box2 = QCheckBox("缓考",self)
        self.btn1 = QPushButton("导出模版",self)
        self.btn2 = QPushButton("导入成绩",self)
        self.init_ui()
        self.set_widget_style()
    def init_ui(self):
        #设置背景色
        pal = QPalette(self.palette())
        pal.setColor(QPalette.Background,QColor(255,255,255))
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        self.btn1.clicked.connect(self.outputTemplates)
        self.btn2.clicked.connect(self.readStudentList)
        self.lab1.move(5,5)
        self.lab2.move(75,20)
        self.lab3.move(40,60)
        self.lab4.move(40,100)
        self.lab4.setFixedSize(200, 100)
        self.lab4.setWordWrap(True)
        self.box1.move(50,210)
        self.box2.move(120,210)
        self.btn1.move(35,245)
        self.btn2.move(120,245)
    def set_widget_style(self):
        tmp = QFont("PingFang SC Regular")
        tmp.setPixelSize(18)
        self.lab2.setFont(tmp)
        f = QFont("PingFang SC Regular")
        f.setPixelSize(16)
        self.lab3.setFont(f)
        self.lab4.setFont(f)
        self.btn1.setFixedWidth(75)
        self.btn2.setFixedWidth(75)
    def outputTemplates(self):
        export_file = QFileDialog.getSaveFileName(self,"学生名单模板")
        file_path = export_file[0]
        if file_path!="":
            path='tree.json'
            f = open(path)
            m = json.load(f)
            title='2018-2019第二学期 钢结构设计原理 试卷分析表'
            class_info='课程：[CE30108]钢结构设计原理（建工、地下、安装方向）        上课班级：208211-002              任课教师：熊刚'
            topic_list=gi.readList(m)[0]
            target_list=gi.readList(m)[1]
            wb=gi.makeExcelTitle(title,class_info,topic_list,target_list)
            wb.save(os.path.join(os.getcwd(),"static/excel/学生名单模板.xls"))

            shutil.copyfile(os.path.join(os.getcwd(),"static/excel/学生名单模板.xls"),file_path)
            QMessageBox.information(self,'导出成功','导出成功',QMessageBox.Yes)


    def readStudentList(self):
        import_file = QFileDialog.getOpenFileName(self,"学生名单","./")
        file_path = import_file[0]
        # 写入学生信息
        stu_info = gsi.get_stu_info(file_path, '考试成绩').tolist()
        for i in range(len(stu_info)):
            stu_info[i][9] = str(stu_info[i][9])
        with open('stu_info.json', 'w') as rgj:
            json.dump(stu_info, rgj)

        # result = self.StudentExcel2List(file_path)
        initscore1 = get.getStudentGrades(file_path, '平时成绩')  # 原始成绩还没正则化
        initscore2 = get.getStudentGrades(file_path, '考试成绩')  # 原始成绩还没正则化
        tree = []
        with open('tree.json') as ij:
            tree = json.load(ij)
        # 将平时成绩与考试成绩正则化之后加入json文件
        usual_performance = rg.regretGrades(tree, initscore1)
        with open('usual_performance.json', 'w') as rgj:
            json.dump(usual_performance, rgj)

        test_score = rg.regretGrades(tree, initscore2)
        with open('test_score.json', 'w') as rgj:
            json.dump(test_score, rgj)

        # 将targetvalue 存入json
        input_list = [usual_performance, test_score]
        tv = target.getTargetValue(tree, input_list)

        with open('tv.json', 'w') as rgj:
            json.dump(tv, rgj)

        stu_info = []
        with open('stu_info.json') as stu:
            stu_info = json.load(stu)
        for i in range(len(stu_info)):
            self.table.setItem(i, 0, QTableWidgetItem(str(i + 1)))
            for j in range(1, 13):
                self.table.setItem(i, j, QTableWidgetItem(str(stu_info[i][j - 1])))

    def StudentExcel2List(self,path):
        df = pd.read_excel(path)
        df_li = df.values.tolist()
        result = []
        for s_li in df_li:
            result.append(s_li)
        return result[1:]
    def get_widget_pointer(self,pointer):
        self.table = pointer
class TemplatesResult(QWidget):
    def __init__(self,parent=None):
        super().__init__(parent=parent)
        self.resize(250,305)
        self.pic = QPixmap("static/statistics.jpg")
        self.pic = self.pic.scaled(37, 27, Qt.KeepAspectRatio)
        self.lab1 = QLabel(self)
        self.lab1.setPixmap(self.pic)
        self.lab2 = QLabel(self)
        self.lab2.setText("结果生成")
        self.box1 = QCheckBox("留学生（包含打勾）",self)
        self.box2 = QCheckBox("学院筛选",self)
        self.btn1 = QPushButton("导出存档报告",self)
        self.btn2 = QPushButton("导出提交报告",self)
        self.btn3 = QPushButton("预览",self)
        self.btn4 = QPushButton("导出",self)
        self.line1 = QLineEdit(self)
        self.init_ui()
        self.set_widget_style()
        self.btn4.clicked.connect(self.output)


    def output(self):
        export_file = QFileDialog.getSaveFileName(self,"学生名单模板")
        file_path = export_file[0]
        if file_path!="":
            big.big_function()
            print(file_path)
            combine.zipDir("excel_output", file_path)
            QMessageBox.information(self,'导出成功','导出成功',QMessageBox.Yes)

    def init_ui(self):
        #s设置背景色
        pal = QPalette(self.palette())
        pal.setColor(QPalette.Background,QColor(255,255,255))
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        self.lab1.move(5,5)
        self.lab2.move(80,20)
        self.box1.move(45,80)
        self.box2.move(45,110)
        self.line1.move(135,110)
        self.btn1.move(45,200)
        self.btn2.move(45,240)
        self.btn3.move(45,150)
        self.btn4.move(125,150)
    def set_widget_style(self):
        self.line1.setFixedWidth(60)
        self.btn1.setFixedWidth(150)
        self.btn2.setFixedWidth(150)
        self.btn3.setFixedWidth(70)
        self.btn4.setFixedWidth(70)
        tmp = QFont("PingFang SC Regular",18)
        tmp.setPixelSize(18)
        self.lab2.setFont(tmp)
#学生名单
class StuListWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()
        # pal = QPalette(self.palette())
        # pal.setColor(QPalette.Background,QColor(242,242,242))
        # self.setAutoFillBackground(True)
        # self.setPalette(pal)
        # self.resize(590,390)
        self.layout = QVBoxLayout()
        # self.table = TableStu.TableStuList(self)

        # self.table.move(0,60)
        # self.pic = QPixmap("static/excel.jpg")
        # self.pic = self.pic.scaled(35, 40, Qt.KeepAspectRatio)
        # self.lab1 = QLabel(self)
        # self.lab1.move(5,5)
        # self.lab1.setPixmap(self.pic)
        # self.lab2 = QLabel(self)
        # self.lab2.setText("学生名单")
        # f = QFont("PingFang SC Regular",18)
        # f.setPixelSize(18)
        # self.lab2.setFont(f)
        # self.lab2.move(50,15)
        stu_info = []
        self.table = QTableWidget()
        self.table.setMinimumSize(60, 50)
        self.table.verticalHeader().setVisible(False)
        # self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        with open('stu_info.json') as stu:
            stu_info = json.load(stu)
        self.table.setRowCount(len(stu_info))
        self.table.setColumnCount(len(stu_info[0]))
        for i in range(len(stu_info)):
            self.table.setItem(i, 0, QTableWidgetItem(str(i + 1)))
            for j in range(1, len(stu_info[0]) + 1):
                self.table.setItem(i, j, QTableWidgetItem(str(stu_info[i][j - 1])))
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)

#成绩录入
class ResultWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()
        # pal = QPalette(self.palette())
        # pal.setColor(QPalette.Background, QColor(242, 242, 242))
        # self.setAutoFillBackground(True)
        # self.setPalette(pal)
        # self.resize(590, 390)
        # self.table = TableStu.TableImport(self)
        #
        # self.table.move(0, 60)
        # self.pic = QPixmap("static/upload.jpg")
        # self.pic = self.pic.scaled(45, 40, Qt.KeepAspectRatio)

        self.layout = QVBoxLayout()
        self.up = QHBoxLayout()
        #
        # self.lab1 = QLabel(self)
        # self.lab1.move(5, 5)
        # self.lab1.setPixmap(self.pic)
        # self.lab2 = QLabel(self)
        # self.lab2.setText("成绩录入")
        # f = QFont("PingFang SC", 18)
        # f.setPixelSize(18)
        # self.lab2.setFont(f)
        # self.lab2.move(50, 15)
        self.btn1 = QPushButton("平时成绩", self)
        self.btn2 = QPushButton("期末成绩", self)
        # self.btn1.move(360, 10)
        # self.btn2.move(460, 10)
        self.btn1.clicked.connect(self.print_usual)
        self.btn2.clicked.connect(self.print_test)
        self.up.addWidget(self.btn1)
        self.up.addWidget(self.btn2)
        self.layout.addLayout(self.up)

        self.down = QHBoxLayout()
        self.table = QTableWidget()
        self.table = QTableWidget()
        self.table.setMinimumSize(60, 50)
        self.table.verticalHeader().setVisible(False)
        # self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.table.setRowCount(7)
        self.table.setColumnCount(10)
        self.down.addWidget(self.table)
        self.layout.addWidget(self.table)

        self.setLayout(self.layout)

    def print_usual(self):
        stu_info = []
        with open('stu_info.json') as st:
            stu_info = json.load(st)

        usual_performance = []
        with open('usual_performance.json') as ij:
            usual_performance = json.load(ij)

        self.table.setColumnCount(3 + len(usual_performance[0]))
        self.table.setRowCount(len(usual_performance))

        for i in range(len(stu_info)):
            self.table.setItem(i, 0, QTableWidgetItem(str(i)))
            self.table.setItem(i, 1, QTableWidgetItem(str(stu_info[i][0])))
            self.table.setItem(i, 2, QTableWidgetItem(str(stu_info[i][1])))

        for i in range(0, len(usual_performance)):
            for j in range(0, len(usual_performance[0])):
                self.table.setItem(i, j + 3, QTableWidgetItem(str(usual_performance[i][j])))

    def print_test(self):
        stu_info = []
        with open('stu_info.json') as st:
            stu_info = json.load(st)

        test_score = []
        with open('test_score.json') as ij:
            test_score = json.load(ij)

        self.table.setColumnCount(3 + len(test_score[0]))
        self.table.setRowCount(len(test_score))

        for i in range(len(stu_info)):
            self.table.setItem(i, 0, QTableWidgetItem(str(i)))
            self.table.setItem(i, 1, QTableWidgetItem(str(stu_info[i][0])))
            self.table.setItem(i, 2, QTableWidgetItem(str(stu_info[i][1])))

        for i in range(0, len(test_score)):
            for j in range(0, len(test_score[0])):
                self.table.setItem(i, j + 3, QTableWidgetItem(str(test_score[i][j])))

class ResultCreate(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.layout = QHBoxLayout()
        self.layout.setSpacing(20)
        # 第一列按钮布局管理
        hLayout1 = QVBoxLayout()
        table = QTableWidget()
        table.setRowCount(4)
        table.setColumnCount(9)
        table.setMinimumSize(60, 50)
        table.setHorizontalHeaderLabels(
            ["毕业目标", "0-0.59", "0.60-0.69", "0.70-0.79", "0.80-0.89", "0.90-1.00", "平均值", "最低值", "最高值"])
        table.verticalHeader().setVisible(False)
        table.setItem(0, 0, QTableWidgetItem("目标1"))
        table.setItem(1, 0, QTableWidgetItem("目标2"))
        table.setItem(2, 0, QTableWidgetItem("目标3"))
        table.setItem(3, 0, QTableWidgetItem("目标4"))
        table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hLayout1.addWidget(table)

        # 12张图
        inside = QGridLayout()
        for i in range(3):
            for j in range(4):
                lab = QLabel()
                self.png = QPixmap("excel_output/img/bar/分布柱状图.png")
                lab.setPixmap(self.png)
                lab.setMinimumSize(60, 30)
                lab.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
                lab.setScaledContents(True)
                inside.addWidget(lab, i, j)
        hLayout1.addLayout(inside)
        hLayout1.setStretch(0, 1)
        hLayout1.setStretch(1, 1)
        # hLayout1.addStretch(2)
        # 第二行按钮布局管理
        hLayout2 = QVBoxLayout()
        lable = QTextEdit("请在这里输入点评")
        lable.setMinimumSize(80, 30)
        lable.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hLayout2.addWidget(lable)
        lab = QLabel()
        self.png = QPixmap("excel_output/img/bar/分布柱状图.png")
        lab.setPixmap(self.png)
        lab.setScaledContents(True)

        lab.setMinimumSize(60, 30)
        lab.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hLayout2.addWidget(lab)
        hLayout2.setStretch(0, 1)
        hLayout2.setStretch(1, 1)
        # 整体水平布局管理
        self.layout.addLayout(hLayout1)
        self.layout.addLayout(hLayout2)

        self.layout.setStretch(0, 2)
        self.layout.setStretch(1, 1)
        self.setLayout(self.layout)

if __name__=="__main__":
    app = QApplication(sys.argv)
    window = Test()
    window.show()
    sys.exit(app.exec_())